import axios from "axios";
import { Message } from 'element-ui';
import router from '../router'


// 创建一个axios实例
const service = axios.create({
    baseURL: '/flyduck-platform',
    timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
    config=>{
        //如果存在，请求携带token
        if(window.sessionStorage.getItem('token')){
            config.headers['Authorization'] = window.sessionStorage.getItem('token')
        }
        return config;
    },
    error => {
        console.log(error)
    }
)
// 响应拦截器
service.interceptors.response.use(
        // 后端接口成功返回
        success=>{
            if(success.status && success.status == 200){
                if(success.data.code==200){
                    if(success.data.message){
                        Message.success({message:success.data.message});
                    }
                    //200返回数据
                    return success.data.data;
                }else {
                    debugger
                    Message.error({message:success.data.message});
                    if(success.data.code==401){
                        //401未登录,跳转login
                        router.replace('/');
                    }
                    return;
                }
            }
        },
         // 后端接口访问失败(比如服务器挂机)
        error => {
            Message.error({message:'服务器未启动!'});
            return;
        }
)

export default service
